package com.fanfan.SmartPensionSystembackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fanfan.SmartPensionSystembackend.entity.*;
import com.fanfan.SmartPensionSystembackend.mapper.ElderMapper;
import com.fanfan.SmartPensionSystembackend.mapper.BedMapper;
import com.fanfan.SmartPensionSystembackend.mapper.FamilyMapper;
import com.fanfan.SmartPensionSystembackend.service.ElderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class ElderServiceImpl implements ElderService {

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private FamilyMapper familyMapper;

    // 新增老人信息
    @Override
    @Transactional
    public String checkInElder(CheckInfo checkInfo) {
        try {
            Elder elder = checkInfo.getCheckInfo();

            // 生成 elderId
            String maxElderId = elderMapper.getMaxElderId();
            String newElderId = generateNextId(maxElderId);
            elder.setElderId(newElderId);

            // 查询床信息
            BedInfo bedInfo = elder.getBedInfo();
            // 查询床信息
            Bed bed = bedMapper.selectOne(new LambdaQueryWrapper<Bed>()
                    .eq(Bed::getBedNo, bedInfo.getBedNo().trim())
                    .eq(Bed::getBuildingNo, bedInfo.getBuildingNo().trim())
                    .eq(Bed::getFloorNo, bedInfo.getFloorNo().trim())
                    .eq(Bed::getRoomNo, bedInfo.getRoomNo().trim()));

            if (bed == null) throw new RuntimeException("床信息无效");

            // 新增校验：如果床位状态为 "occupied"，直接拒绝入住
            if ("已使用".equals(bed.getStatus())) {
                throw new RuntimeException("床位已被占用，请选择其他床位");
            }

            String bedId = bed.getBedId();  // 获取床位ID

            // 更新 bed 表的 status 和 gender
            // ElderServiceImpl.java 中的更新逻辑
            // 更新 bed 表的 status 和 gender
            UpdateWrapper<Bed> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda()
                    .eq(Bed::getBedNo, bedInfo.getBedNo().trim())
                    .set(Bed::getStatus, "已使用")        // 强制设置为占用状态
                    .set(Bed::getGender, elder.getBaseInfo().getGender());

            bedMapper.update(null, updateWrapper);

            // 设置 bedId 到 baseInfo 并插入 elder 数据
            BaseInfo baseInfo = elder.getBaseInfo();
            baseInfo.setBedId(bedId);  // 确保 bedId 是字符串类型（如 "0001"）
            elderMapper.insertElder(elder);

            // 插入 family 数据
            List<FamilyInfo> familyInfoList = elder.getFamilyInfo();
            String maxFamilyId = familyMapper.getMaxFamilyId();
            for (FamilyInfo familyInfo : familyInfoList) {
                Family family = new Family();
                maxFamilyId = generateNextId(maxFamilyId);
                family.setFamilyId(maxFamilyId);
                family.setElderId(newElderId);
                family.setName(familyInfo.getName());
                family.setRelationship(familyInfo.getRelationship());
                family.setPhone(familyInfo.getPhone());
                familyMapper.insert(family);
            }

            return newElderId;
        } catch (Exception e) {
            throw new RuntimeException("入住失败：" + e.getMessage());
        }
    }

    // ID 生成工具方法
    private String generateNextId(String currentId) {
        if (currentId == null || currentId.isEmpty()) return "0001";
        int num = Integer.parseInt(currentId) + 1;
        return String.format("%04d", num);  // 格式化为四位数字符，如 "0002"
    }

    // 获取老人详细信息
    @Override
    public Elder getElderWithDetails(String elderId) {
        Elder elder = new Elder();
        // 1. 查询老人基本信息
        BaseInfo baseinfo = elderMapper.selectById(elderId);
//        Elder elder = elderMapper.selectById(elderId);
        elder.setBaseInfo(baseinfo);
        System.out.println("查找到的elder = " + baseinfo);
        if (baseinfo == null) throw new RuntimeException("老人不存在");

        // 2. 查询床位信息
        BedInfo bedInfo = bedMapper.getBedInfoByBedId(baseinfo.getBedId());
        elder.setBedInfo(bedInfo);

        // 3. 查询家属信息
        List<FamilyInfo> familyInfo = familyMapper.getFamilyByElderId(elderId);
        elder.setFamilyInfo(familyInfo);

        return elder;
    }

    // 更新老人信息
    @Override
    @Transactional
    public boolean updateElderInfo(CheckInfo checkInfo) {
        try {
            Elder elder = checkInfo.getCheckInfo();
            String elderId = elder.getElderId();
            BaseInfo baseInfo = elder.getBaseInfo();
            BedInfo bedInfo = elder.getBedInfo();
            List<FamilyInfo> familyInfoList = elder.getFamilyInfo();
            System.out.println("elder = " + elder);
            System.out.println("baseInfo = " + baseInfo);
            System.out.println("bedInfo = " + bedInfo);
            System.out.println("familyInfoList = " + familyInfoList);

            // 更新 elder 表
            if (baseInfo != null) {
                baseInfo.setElderId(elderId);
                elderMapper.updateElderInfo(baseInfo);
            }

            // 更新 bed 表
            if (bedInfo != null) {
                // 从 elder 表中获取原来的 bedId
                BaseInfo existingBaseInfo = elderMapper.selectById(elderId);
                String oldBedId = existingBaseInfo.getBedId();

                // 清空原来的床位状态和性别
                if (oldBedId != null) {
                    UpdateWrapper<Bed> clearWrapper = new UpdateWrapper<>();
                    clearWrapper.lambda()
                            .eq(Bed::getBedId, oldBedId)
                            .set(Bed::getStatus, "空")
                            .set(Bed::getGender, null);  // 清空性别信息
                    bedMapper.update(null, clearWrapper);
                }

                // 查询新的床位信息
                Bed newBed = bedMapper.selectOne(new LambdaQueryWrapper<Bed>()
                        .eq(Bed::getBedNo, bedInfo.getBedNo().trim())
                        .eq(Bed::getBuildingNo, bedInfo.getBuildingNo().trim())
                        .eq(Bed::getFloorNo, bedInfo.getFloorNo().trim())
                        .eq(Bed::getRoomNo, bedInfo.getRoomNo().trim()));

                if (newBed == null) throw new RuntimeException("新床位信息无效");

                // 更新新床位的状态和性别
                UpdateWrapper<Bed> updateWrapper = new UpdateWrapper<>();
                updateWrapper.lambda()
                        .eq(Bed::getBedId, newBed.getBedId())
                        .set(Bed::getStatus, "已使用")
                        .set(Bed::getGender, baseInfo.getGender());

                bedMapper.update(null, updateWrapper);

                // 将新床位的 bedId 更新到 elder 表
                baseInfo.setBedId(newBed.getBedId());
                System.out.println("baseInfo信息 = " + baseInfo);
                elderMapper.updateElderInfoWidthBedId(baseInfo);  // 确保 bedId 更新到 elder 表
            }

            // 更新 family 表
            if (familyInfoList != null) {
                for (FamilyInfo familyInfo : familyInfoList) {
                    familyInfo.setElderId(elderId);
                    System.out.println("familyInfo信息 = " + familyInfo);
                    familyMapper.updateFamilyInfo(familyInfo);
                }
            }

            return true;
        } catch (Exception e) {
            throw new RuntimeException("更新老人信息失败：" + e.getMessage());
        }
    }

    // 删除老人信息
    @Override
    @Transactional
    public boolean deleteElderInfo(String elderId) {
        try {
            // 先删除 family 表
            familyMapper.deleteByElderId(elderId);

            // 删除 elder 表
            elderMapper.deleteById(elderId);

            // 删除 bed 表
            BaseInfo baseInfo = elderMapper.selectById(elderId);
            if (baseInfo != null) {
                String bedId = baseInfo.getBedId();
                if (bedId != null) {
                    // 更新床位状态为空
                    UpdateWrapper<Bed> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.lambda()
                            .eq(Bed::getBedId, bedId)
                            .set(Bed::getStatus, "空")
                            .set(Bed::getGender, null);
                    bedMapper.update(null, updateWrapper);
                }
            }

            return true;
        } catch (Exception e) {
            throw new RuntimeException("删除老人信息失败：" + e.getMessage());
        }
    }
}